package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.ArithUtils;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.common.util.Constant;
import com.recharge.common.util.RedisUtil;
import com.recharge.core.entity.*;
import com.recharge.core.entity.GoodsMerchantEntity;
import com.recharge.core.mapper.GoodsMerchantMapper;
import com.recharge.domain.query.GoodsMerchantQueryDO;
import com.recharge.domain.vo.*;
import com.recharge.domain.vo.GoodsMerchantDO;
import com.recharge.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2020-09-28
 */
@Service
public class GoodsMerchantServiceImpl extends ServiceImpl<GoodsMerchantMapper, GoodsMerchantEntity> implements GoodsMerchantService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsGroupService goodsGroupService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private GoodsProviderService goodsProviderService;


    public ResultDO edit(GoodsMerchantDO domain) {

        GoodsMerchantEntity entity = new GoodsMerchantEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setModifiDate(Calendar.getInstance().getTime());

        result = this.get(entity.getId());
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        GoodsMerchantDO goodsMerchant = (GoodsMerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
        List<GoodsDO> goodsList = new ArrayList<>();
        GoodsDO goodsDO = new GoodsDO();
        goodsDO.setId(goodsMerchant.getGoodsId());
        goodsList.add(goodsDO);
        //查询该商户的亏损范围
        result = merchantService.get(goodsMerchant.getMerchantId());
        if(!result.isSuccess()){
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        MerchantDO mDomain = (MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
        //判断折扣是否通过
        result = checkDiscount(result, goodsList, entity.getDiscount(), mDomain.getLossType());
        if(!result.isSuccess()){
            return result;
        }

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_EDIT_ERROR.getCode() + " msg" + ErrorCode.GOODS_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Override
    public ResultDO editByGoodsId(GoodsMerchantDO updateDomain, String goodsId) {
        GoodsMerchantEntity entity = new GoodsMerchantEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, updateDomain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setModifiDate(Calendar.getInstance().getTime());

        boolean res = false;
        try {
            res = this.update(entity, Wrappers.<GoodsMerchantEntity>lambdaQuery().eq(GoodsMerchantEntity::getGoodsId, goodsId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        return result;
    }

    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        GoodsMerchantEntity entity = null;

        try {
            entity = this.getById(id);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        GoodsMerchantDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }


    @Override
    public ResultDO findList(GoodsMerchantDO findDomain) {
        GoodsMerchantEntity entity = new GoodsMerchantEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, findDomain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<GoodsMerchantEntity> wrapper = new QueryWrapper<GoodsMerchantEntity>(entity);
        wrapper.lambda().eq(GoodsMerchantEntity::getIsDelete, Constant.IS_DELETE_FALSE);
        if(StringUtils.isNotEmpty(findDomain.getGoodsId())){
            wrapper.lambda().eq(GoodsMerchantEntity::getGoodsId, findDomain.getGoodsId());
        }

        wrapper.lambda().orderByAsc(GoodsMerchantEntity::getDiscount);

        List<GoodsMerchantEntity> list = null;
        try {
            list = baseMapper.selectList(wrapper);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<GoodsMerchantDO> domainList = getDomainList(list);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domainList);

        return result;
    }

    @Override
    public ResultDO saveBatch(List<GoodsMerchantDO> domainList) {

        ResultDO result = new ResultSupport();

        List<GoodsDO> goodsList = new ArrayList<>();
        List<Float> discountList = new ArrayList<>();
        List<String> merchantIdList = new ArrayList<>();
        List<GoodsMerchantEntity> insertDomain = domainList.stream().map( item -> {
            GoodsMerchantEntity entity = new GoodsMerchantEntity();
            BeanUtilsExtends.copyProperties(entity, item);
//
//            GoodsDO goods = new GoodsDO();
//            goods.setId(entity.getGoodsId());
//            goodsList.add(goods);
//            discountList.add(entity.getDiscount());
//
//            merchantIdList.add(entity.getMerchantId());
            return entity;
        }).collect(Collectors.toList());
//        //查询该商户的亏损范围
//        result = merchantService.get(merchantIdList.get(0));
//        if(!result.isSuccess()){
//            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return result;
//        }
//        MerchantDO mDomain = (MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
//        //判断折扣是否通过
//        result = checkDiscount(result, goodsList, discountList.get(0), mDomain.getLossType());
//        if(!result.isSuccess()){
//            return result;
//        }
        try {
            this.saveBatch(insertDomain);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    @Override
    public ResultDO remove(String merchantId, String groupId, String modifier) {
        ResultDO result = new ResultSupport();
        GoodsMerchantEntity entity = new GoodsMerchantEntity();
        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);
        result = goodsService.findByGroupId(groupId);
        if(!result.isSuccess()){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<GoodsDO> goodsList = (List<GoodsDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
        if(goodsList == null || goodsList.size() <=0){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        try {
            goodsList.stream().forEach( item -> {
                baseMapper.update(entity, Wrappers.<GoodsMerchantEntity>lambdaQuery().eq(GoodsMerchantEntity::getMerchantId, merchantId).eq(GoodsMerchantEntity::getGoodsId, item.getId()));
            });
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }


    public ResultDO find(GoodsMerchantQueryDO query) {
        GoodsMerchantEntity entity = new GoodsMerchantEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<GoodsMerchantEntity> wrapper = new QueryWrapper<GoodsMerchantEntity>(entity);

        if(StringUtils.isNotEmpty(query.getGoodsName())){
            wrapper.lambda().like(GoodsMerchantEntity::getGoodsName, query.getGoodsName());
        }
        if(StringUtils.isNotEmpty(query.getGroupName())){
            wrapper.lambda().like(GoodsMerchantEntity::getGroupName, query.getGroupName());
        }
        if(StringUtils.isNotEmpty(query.getMerchantName())){
            wrapper.lambda().like(GoodsMerchantEntity::getMerchantName, query.getMerchantName());
        }
        if(query.getGroupId() != null){
            wrapper.lambda().eq(GoodsMerchantEntity::getGroupId, query.getGroupId());
        }
        if(query.getMerchantId() != null){
            wrapper.lambda().eq(GoodsMerchantEntity::getMerchantId, query.getMerchantId());
        }
        if(query.getHierarchy() != null && query.getHierarchy() == 1){
            wrapper.lambda().groupBy(GoodsMerchantEntity::getMerchantId);
        }
        if(query.getHierarchy() != null && query.getHierarchy() == 2){
            wrapper.lambda().groupBy(GoodsMerchantEntity::getMerchantId, GoodsMerchantEntity::getGroupId);
        }
        if(query.getHierarchy() != null && query.getHierarchy() == 3){
            wrapper.lambda().orderByAsc(GoodsMerchantEntity::getDenomination);
        }
        Page<GoodsMerchantEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<GoodsMerchantEntity> iPage = null;

        try {
            iPage = baseMapper.selectOtherPage(page, wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<GoodsMerchantDO> doList = getDomainList(iPage.getRecords());

        if(query.getHierarchy() != null && query.getHierarchy() == 2 && doList != null && doList.size() >0){
            //查询这条数据在的旧折扣
            try {
                doList.stream().forEach( item -> {
                    QueryWrapper<GoodsMerchantEntity> queryWrapper = new QueryWrapper<GoodsMerchantEntity>();
                    queryWrapper.lambda().eq(GoodsMerchantEntity::getMerchantId, item.getMerchantId());
                    queryWrapper.lambda().eq(GoodsMerchantEntity::getGroupId, item.getGroupId());
                    Page<GoodsMerchantEntity> queryPage = new Page<>(query.getCurrentPage(),100);
                    IPage<GoodsMerchantEntity> resultData = baseMapper.selectOtherPage(queryPage, queryWrapper);
                    List<GoodsMerchantEntity> goodsProviderEntityList = resultData.getRecords();
                    if(goodsProviderEntityList != null && goodsProviderEntityList.size() >0){
                        goodsProviderEntityList.stream().forEach( obj -> {
                            if(item.getAfterDiscount() != null && item.getAfterDiscount().floatValue() != obj.getDiscount().floatValue()){
                                item.setRed(true);
                            }
                        });
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                logger.debug("设置是否显示红色错误");
            }
        }

        PageDO<GoodsMerchantDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    @Override
    public ResultDO getGoodsGroup(String merchantId) {
        ResultDO result = new ResultSupport();
        List<GoodsGroupEntity> goodsList = null;
        try {
            goodsList = baseMapper.selectGoodsGroupByMerchantId(merchantId);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<GoodsGroupDO> domainList = null;
        if(goodsList != null && !goodsList.isEmpty()){
            domainList = goodsList.stream().map( item -> {
                GoodsGroupDO goodsGroupDO= new GoodsGroupDO();
                return BeanUtilsExtends.copyProperties(goodsGroupDO, item) ? goodsGroupDO : null;
            }).collect(Collectors.toList());
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, domainList);

        return result;
    }
    @Override
    public ResultDO updateDiscountBatch(String groupId, String merchantId, Float discount, String userName) {
        GoodsMerchantEntity entity = new GoodsMerchantEntity();

        ResultDO result = new ResultSupport();
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        result = goodsService.findByGroupId(groupId);
        if(!result.isSuccess()){
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        List<GoodsDO> goodsList = (List<GoodsDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);

        if(goodsList == null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        entity.setDiscount(discount);
        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(userName);
        //查询该商户的亏损范围
        result = merchantService.get(merchantId);
        if(!result.isSuccess()){
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        MerchantDO mDomain = (MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
        //判断折扣是否通过
        result = checkDiscount(result, goodsList, discount, mDomain.getLossType());
        if(!result.isSuccess()){
            return result;
        }
        try {
            for (GoodsDO goods : goodsList) {
                //设置lastDiscount 为这次批量修改的结果
                entity.setAfterDiscount(discount);
                baseMapper.update(entity, Wrappers.<GoodsMerchantEntity>lambdaQuery().eq(GoodsMerchantEntity::getMerchantId, merchantId).eq(GoodsMerchantEntity::getGoodsId, goods.getId()));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    @Override
    public ResultDO updateStatus(String merchantId, String goodsIds, Integer status, String modifier) {
        GoodsMerchantEntity entity = new GoodsMerchantEntity();
        ResultDO result = new ResultSupport();
        if(StringUtils.isEmpty(merchantId) || (status != Constant.MERCHANT_GOODS_GROUP_STATUS_1 && status != Constant.MERCHANT_GOODS_GROUP_STATUS_2)){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }

        String[] goodsIdArray = goodsIds.split(",");
        entity.setStatus(status);

        try {
            for (String goodsId : goodsIdArray) {
                baseMapper.update(entity, Wrappers.<GoodsMerchantEntity>lambdaQuery().eq(GoodsMerchantEntity::getMerchantId, merchantId).eq(GoodsMerchantEntity::getGoodsId, goodsId));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    public ResultDO getGoodsMerchantDiscount(String goodsId, String merchantId) {

        ResultDO result = new ResultSupport();
        GoodsMerchantEntity entity = null;
        try {
            entity = this.baseMapper.selectOne(Wrappers.<GoodsMerchantEntity>lambdaQuery()
                    .eq(GoodsMerchantEntity::getGoodsId, goodsId)
                    .eq(GoodsMerchantEntity::getMerchantId, merchantId)
                    .eq(GoodsMerchantEntity::getStatus, Constant.MERCHANT_GOODS_GROUP_STATUS_1)
                    .eq(GoodsMerchantEntity::getIsDelete, Constant.IS_DELETE_FALSE));
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        if(entity == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_MERCHANT_DISCOUNT_ERROR);
            return result;
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getDiscount());
        return result;
    }

    @Override
    public ResultDO listByMerchantId(String merchantId) {

        ResultDO result = new ResultSupport();

        List<GoodsMerchantEntity> list = null;

        QueryWrapper<GoodsMerchantEntity> wrappers = new QueryWrapper();

        wrappers.lambda().eq(GoodsMerchantEntity::getIsDelete, Constant.IS_DELETE_FALSE).eq(GoodsMerchantEntity::getMerchantId, merchantId);
        try {
            list = this.baseMapper.selectList(wrappers);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<GoodsMerchantDO> doList = getDomainList(list);

        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO removeByGoodsId(String goodId, String modifier) {

        ResultDO result = new ResultSupport();

        GoodsMerchantEntity entity = new GoodsMerchantEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);
        boolean res = false;
        try {
            res = this.update(entity, Wrappers.<GoodsMerchantEntity>lambdaQuery().eq(GoodsMerchantEntity::getGoodsId, goodId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO addBatch(GoodsMerchantDO param) {
        ResultDO result = new ResultSupport();

        if(StringUtils.isEmpty(param.getGroupIds()) || StringUtils.isEmpty(param.getMerchantId())){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }
        String[] groupArray =  param.getGroupIds().split(",");

        //查询指定商品组下面的列表
        List<GoodsDO> goodsList = new ArrayList<>();
        try {
            for (String groupId : groupArray) {
                ResultDO selectResult = goodsService.findByGroupId(groupId);
                if(!result.isSuccess()){
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
                List<GoodsDO> addList = (List<GoodsDO>) selectResult.getModel(ResultDO.FIRST_MODEL_KEY);

                selectResult = goodsGroupService.get(groupId);
                if(!result.isSuccess()){
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
                GoodsGroupDO goodsGroup = (GoodsGroupDO) selectResult.getModel(ResultDO.FIRST_MODEL_KEY);

                if(addList != null && addList.size() >0){
                    addList.stream().forEach( item -> {
                        if(goodsGroup.getUnit() == Constant.UNIT_SCALE){
                            item.setDiscount(Float.valueOf(String.valueOf(ArithUtils.div(goodsGroup.getValueData(), 10000))));
                        }
                    });
                    goodsList.addAll(addList);
                }
            }
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        if(goodsList == null || goodsList.size() <= 0){
            return result;
        }
        //查询该商户的亏损范围
        result = merchantService.get(param.getMerchantId());
        if(!result.isSuccess()){
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        MerchantDO mDomain = (MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
//        //判断折扣是否通过
//        result = checkDiscount(result, goodsList, param.getDiscount(), mDomain.getLossType());
//        if(!result.isSuccess()){
//            return result;
//        }
        List<GoodsMerchantEntity> goodsMerchantList = null;
        try {
            goodsMerchantList = baseMapper.selectList(Wrappers.<GoodsMerchantEntity>lambdaQuery().eq(GoodsMerchantEntity::getMerchantId, param.getMerchantId()).eq(GoodsMerchantEntity::getIsDelete, Constant.IS_DELETE_FALSE
            ));
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<String> addGoodsList = new ArrayList<>();
        List<String> delGoodsList = new ArrayList<>();
        if(goodsMerchantList != null && goodsMerchantList.size() > 0){
            //筛选掉取消勾选的
            List<String> goodsIdList = goodsList.stream().map(GoodsDO::getId).collect(Collectors.toList());
            addGoodsList.addAll(goodsIdList);
            List<String> oldGoodsIdList = goodsMerchantList.stream().map(GoodsMerchantEntity::getGoodsId).collect(Collectors.toList());
            delGoodsList.addAll(oldGoodsIdList);
            addGoodsList.removeAll(oldGoodsIdList);
            delGoodsList.removeAll(goodsIdList);
        } else {
            addGoodsList = goodsList.stream().map(GoodsDO::getId).collect(Collectors.toList());
        }
        if(addGoodsList != null && addGoodsList.size() > 0){
            List<String> finalAddGoodsList = addGoodsList;
            List<GoodsDO> addGoodsDomain = goodsList.stream().filter( item -> {
                return finalAddGoodsList.contains(item.getId());
            }).collect(Collectors.toList());
            try {
                this.saveBatch(addGoodsDomain.stream().map( item -> {
                    GoodsMerchantEntity entity = new GoodsMerchantEntity();
                    entity.setCreateDate(Calendar.getInstance().getTime());
                    entity.setModifiDate(entity.getCreateDate());
                    entity.setModifier(param.getCreator());
                    entity.setGoodsId(item.getId());
                    entity.setDiscount(item.getDiscount());
                    entity.setMerchantId(param.getMerchantId());
                    //设置lastDiscount 为这次批量修改的结果
                    entity.setAfterDiscount(item.getDiscount());
                    return entity;
                }).collect(Collectors.toList()));
            } catch(Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        if(delGoodsList != null && delGoodsList.size() > 0){
            try {
                GoodsMerchantEntity updateEntity = new GoodsMerchantEntity();
                updateEntity.setIsDelete(Constant.IS_DELETE);
                updateEntity.setModifier(param.getModifier());
                for (String goodsId : delGoodsList) {
                    baseMapper.update(updateEntity, Wrappers.<GoodsMerchantEntity>lambdaQuery().eq(GoodsMerchantEntity::getMerchantId, param.getMerchantId()).eq(GoodsMerchantEntity::getGoodsId, goodsId));
                }
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }

        }
        return result;
    }

    private GoodsMerchantDO getDomain(GoodsMerchantEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        GoodsMerchantDO domain = new GoodsMerchantDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<GoodsMerchantDO> getDomainList(List<GoodsMerchantEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<GoodsMerchantDO> doList = new ArrayList<GoodsMerchantDO>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(GoodsMerchantEntity entity : list) {

                GoodsMerchantDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }

    private ResultDO checkDiscount(ResultDO result, List<GoodsDO> goodsList,float discount, int lossType){
        //查询这里商品列表是否在供应商中关联
        List<GoodsProviderDO> goodsProviderList = new ArrayList<>();
        try {
            for (GoodsDO goods : goodsList) {
                ResultDO selectResult = goodsProviderService.list(goods.getId());
                if(!result.isSuccess()){
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
                List<GoodsProviderDO> addList = (List<GoodsProviderDO>) selectResult.getModel(ResultDO.FIRST_MODEL_KEY);
                if(addList != null && addList.size() >0){
//                    goodsProviderList.addAll(addList);
                    goodsProviderList.add(addList.get(0));
                }
            }
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        //判断设置的代理折扣是否能通过供应商设置的亏损方式
        if(goodsProviderList != null && goodsProviderList.size() >0){
            for (GoodsProviderDO obj : goodsProviderList) {
//                if(obj.getLossType() == Constant.LOSS_TYPE_1) continue;
//                if(obj.getLossType() == Constant.LOSS_TYPE_0){
//                    if(obj.getCostDiscount().floatValue() >= discount) continue;
//                    result.setSuccess(false);
//                    ErrorCode errorCode = ErrorCode.SYSTEM_EXCEPTION;
//                    errorCode.setMsg("商品组存在商品:" + obj.getGoodsId() + "，在供货商:" + obj.getProviderName() + "中，不允许亏损可平价。供货商折扣:" + obj.getCostDiscount() * 100 + "%");
//                    result.setErrorCode(errorCode);
//                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
//                    return result;
//                }
//                if(obj.getLossType() == Constant.LOSS_TYPE_2){
//                    if(obj.getCostDiscount().floatValue() > discount) continue;
//                    result.setSuccess(false);
//                    ErrorCode errorCode = ErrorCode.SYSTEM_EXCEPTION;
//                    errorCode.setMsg("商品组存在商品:" + obj.getGoodsId() + "，在供货商:" + obj.getProviderName() + "中，不允许亏损只能盈利。供货商折扣:" + obj.getCostDiscount() * 100 + "%");
//                    result.setErrorCode(errorCode);
//                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
//                    return result;
//                }
                if(lossType == Constant.LOSS_TYPE_1) continue;
                if(lossType == Constant.LOSS_TYPE_0){
                    if(obj.getCostDiscount().floatValue() <= discount) continue;
                    result.setSuccess(false);
                    ErrorCode errorCode = ErrorCode.GOODS_EDIT_DISCOUNT_ERROR;
                    errorCode.setMsg("折扣过低，亏损范围：不允许亏损可平价。成本折扣:" + obj.getCostDiscount() * 100 + "%");
                    result.setErrorCode(errorCode);
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    return result;
                }
                if(lossType == Constant.LOSS_TYPE_2){
                    if(obj.getCostDiscount().floatValue() < discount) continue;
                    result.setSuccess(false);
                    ErrorCode errorCode = ErrorCode.GOODS_EDIT_DISCOUNT_ERROR;
                    errorCode.setMsg("折扣过低，亏损范围：不允许亏损只能盈利。成本折扣:" + obj.getCostDiscount() * 100 + "%");
                    result.setErrorCode(errorCode);
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    return result;
                }
            }
        }
        return result;
    }
}
